﻿Namespace IMDB

    Friend Class MILHelper
        Public Enum ElementSearchMode
            Exact
            StartsWith
        End Enum
        Public Shared Function FindElementByText(ByVal elements As MIL.Html.HtmlNodeCollection, ByVal text As String) As MIL.Html.HtmlElement
            Return FindElementByText(elements, text, ElementSearchMode.Exact)
        End Function

        Public Shared Function FindElementByText(ByVal elements As MIL.Html.HtmlNodeCollection, ByVal text As String, ByVal mode As ElementSearchMode) As MIL.Html.HtmlElement
            For Each clsNode As MIL.Html.HtmlNode In elements
                Dim clsElement As MIL.Html.HtmlElement = TryCast(clsNode, MIL.Html.HtmlElement)
                If clsElement IsNot Nothing Then
                    Dim strText As String = clsElement.Text.ToLower.Trim
                    Select Case mode
                        Case ElementSearchMode.Exact
                            If strText = text Then Return clsElement
                        Case ElementSearchMode.StartsWith
                            If strText.StartsWith(text) Then Return clsElement
                    End Select
                    Dim clsRes As MIL.Html.HtmlElement = FindElementByText(clsElement.Nodes, text)
                    If clsRes IsNot Nothing Then Return clsRes
                End If
            Next
            Return Nothing
        End Function

        Public Shared Function FindElement(ByVal nodes As MIL.Html.HtmlNodeCollection, ByVal name As String, ByVal attrName As String, ByVal attrValue As String) As MIL.Html.HtmlElement
            For Each clsNode As MIL.Html.HtmlNode In nodes
                If TypeOf clsNode Is MIL.Html.HtmlElement Then
                    Dim clsElement As MIL.Html.HtmlElement = CType(clsNode, MIL.Html.HtmlElement)
                    If clsElement.Name.ToLower = name Then
                        For Each clsAttr As MIL.Html.HtmlAttribute In clsElement.Attributes
                            If clsAttr.Name.ToLower.Trim = attrName Then
                                If clsAttr.Value.ToLower.Trim.Replace("""", String.Empty) = attrValue Then
                                    Return clsElement
                                End If
                            End If
                        Next
                    End If
                    Dim clsRes As MIL.Html.HtmlElement = FindElement(clsElement.Nodes, name, attrName, attrValue)
                    If clsRes IsNot Nothing Then Return clsRes
                End If
            Next
            Return Nothing
        End Function

    End Class

End Namespace